package com.example.demo.gateway.core;

import com.example.demo.gateway.core.annotation.MicroServiceMapping;
import org.reflections.Reflections;
import org.reflections.scanners.FieldAnnotationsScanner;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ConfigurationBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;


/**
 * @Auther: miaoguoxin
 * @Date: 2020/4/14 22:09
 * @Description:
 */
@Component
public class MappingRegister implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private ApplicationContext applicationContext;

    private Map<String,ServiceMetaInfo> serviceMetaInfoMap = new ConcurrentHashMap<>();
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .forPackages("com.example.demo.gateway.support")
                .addScanners(new SubTypesScanner())
                .addScanners(new MethodAnnotationsScanner())
                .addScanners(new FieldAnnotationsScanner()));
        Set<Method> methodsAnnotatedWith = reflections.getMethodsAnnotatedWith(MicroServiceMapping.class);
        for (Method method : methodsAnnotatedWith) {
            Class<?> declaringClass = method.getDeclaringClass();
            System.out.println(declaringClass);
        }

        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(MicroServiceMapping.class);
        for (Class<?> aClass : typesAnnotatedWith) {
            Method[] declaredMethods = aClass.getDeclaredMethods();
            for (Method declaredMethod : declaredMethods) {
                MicroServiceMapping annotation = AnnotationUtils.findAnnotation(declaredMethod, MicroServiceMapping.class);
                Optional.ofNullable(annotation).ifPresent(mapping -> {

                });
            }
        }
    }
}
